<!-- file-view-dialog -->
<template>
  <Dialog
    v-model="visible"
    v-bind="$attrs"
    width="60%"
    :title="title"
    :fullscreenBefore="fullscreenBefore"
    class="file-view-dialog"
    :class="{
      'file-view-text': !!text
    }"
    @close="close"
  >
    <FileView
      ref="fileViewRef"
      v-if="src"
      :src="src"
      :type="type"
      @rendered="renderedHandler"
      @error="errorHandler"
    />
    <pre v-else-if="text">{{ text }}</pre>
    <div v-else-if="html" v-html="html"></div>
  </Dialog>
</template>

<script setup>
import { getFileExtensionByUrl, findType, requestFullScreen } from './utils'
defineOptions({ name: 'FileViewDialog' })
const props = defineProps({
  modelValue: Boolean,
  // 标题
  title: {
    type: String,
    default: '预览'
  },
  type: String,
  // 在线资源
  src: String,
  // 文字
  text: String,
  // 富文本
  html: String
})
const emit = defineEmits(['update:modelValue'])
const fileViewRef = ref(null)
const renderedHandler = () => {
  console.log('rendered')
}
const errorHandler = (error) => {
  console.log('error', error)
}
const currentType = computed(() => {
  const extension = getFileExtensionByUrl(props.src)
  return props.type || findType(extension)
})
const fullscreenBefore = computed(() => {
  let fn = null
  if (currentType.value === 'video') {
    fn = () => {
      requestFullScreen(fileViewRef.value?.instanceRef)
    }
  }
  return fn
})

const close = (val) => {
  const instanceRef = fileViewRef.value?.instanceRef
  // 销毁资源
  instanceRef?.pause?.()
  if (instanceRef?.src && !instanceRef?.$) {
    instanceRef.src = ''
  }
  instanceRef?.load?.()
  instanceRef?.destroy?.()
}
const visible = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  }
})
</script>

<style lang="scss" scoped>
pre {
  font-family: inherit;
  white-space: pre-wrap;
}
</style>
<style lang="scss">
.file-view-dialog {
  .el-dialog__body {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 600px;
    padding: 0 !important;
    overflow-y: auto;
  }

  &.is-fullscreen {
    .file-view,
    .el-dialog__body {
      height: calc(100vh - (var(--el-dialog-padding-primary) * 2) - 54px);
    }
    // .file-view {
    //   overflow: hidden;
    // }
  }

  &.file-view-text {
    .el-dialog__body {
      display: block;
      height: auto;
      padding: 15px !important;
      overflow-y: auto;
    }
  }
}
</style>
